package org.ruiyichen.guizhou.agr.ui.fragment;

import android.graphics.Matrix;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;

import org.ruiyichen.guizhou.agr.R;
import org.ruiyichen.guizhou.agr.base.BaseFragment;
import org.ruiyichen.guizhou.agr.base.DataManger;
import org.ruiyichen.guizhou.agr.bean.Response;
import org.ruiyichen.guizhou.agr.config.Constant;
import org.ruiyichen.guizhou.agr.imp.IIrrigatedAreaFilter;
import org.ruiyichen.guizhou.agr.net.OkHttpManager;
import org.ruiyichen.guizhou.agr.ui.activity.HomeActivity;
import org.ruiyichen.guizhou.agr.ui.mineview.BToast;
import org.ruiyichen.guizhou.agr.utils.StrUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.viewpager.widget.ViewPager;

/**
 * 监测
 */
public class MonitorFragment extends BaseFragment implements View.OnClickListener {

    public TextView[] mBtns;
    private ImageView navigationSlider;
    private ViewPager vp_fragment;
    //fragment的集合，对应每个子页面
    private BaseFragment[] fragments;
    //屏幕宽度
    private int mScreenWidth;
    //偏移量
    private int offset;
    //按键个数
    private final int BTN_SIZE = 2;

    @Override
    public void onResume() {
        super.onResume();
        if (!getUserVisibleHint()) {
            return;
        }
        initData();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            bHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    initData();
                }
            }, 500);
        }
        super.onHiddenChanged(hidden);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mRootView == null) {
            mRootView = inflater.inflate(R.layout.df_fragment_nav_monitor, container, false);
            bOkHttpManager = new OkHttpManager(getActivity(), bHandler);
            initViews();
            initEvents();
            initData();
        }
        //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) mRootView.getParent();
        if (parent != null) {
            parent.removeView(mRootView);
        }
        return mRootView;
    }

    private void initViews() {
        setTitle("监测").setRightImage(0).setRightText(null);
        //获取屏幕宽度
        DisplayMetrics outMetrics = new DisplayMetrics();
        getCustomActivity().getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        mScreenWidth = outMetrics.widthPixels;

        mBtns = new TextView[BTN_SIZE];
        //采集设备
        mBtns[0] = (TextView) mRootView.findViewById(R.id.tv_btn1);
        mBtns[0].setSelected(true);
        //设备控制
        mBtns[1] = (TextView) mRootView.findViewById(R.id.tv_btn2);


        //viewPage
        vp_fragment = (ViewPager) mRootView.findViewById(R.id.vp_fragment);

        //初始化界面
        fragments = new BaseFragment[BTN_SIZE];
        fragments[0] = new CollectDeviceFragment();
        fragments[1] = new ControlDeviceFragment();

        //初始化导航栏滑块
        navigationSlider = (ImageView) mRootView.findViewById(R.id.iv_navigation_slider);
        navigationSlider.getLayoutParams().width = mScreenWidth / fragments.length;
        // 计算偏移量
        offset = mScreenWidth / fragments.length;
        Matrix matrix = new Matrix();
        matrix.postTranslate(offset, 0);
        navigationSlider.setImageMatrix(matrix);

        vp_fragment.setAdapter(new BaseFragmentPageAdapter(getChildFragmentManager(), fragments));

        vp_fragment.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                selectPage(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initEvents() {
        for (int i = 0; i < mBtns.length; i++) {
            mBtns[i].setOnClickListener(this);
        }
    }

    @Override
    public boolean onBackPressed() {
        return false;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_btn1:
                selectPage(0);
                break;
            case R.id.tv_btn2:
                selectPage(1);
                break;
        }
    }

    private int curr_page;

    private void selectPage(int page) {
        if (page == curr_page) {
            return;
        }
        //底部标签选择状态
        for (int i = 0; i < mBtns.length; i++) {
            mBtns[i].setSelected(i == page);
        }
        //滑块动画
        Animation animation = new TranslateAnimation(offset * curr_page, offset * page, 0, 0);
        animation.setFillAfter(true);// True:图片停在动画结束位置
        animation.setDuration(300);
        navigationSlider.startAnimation(animation);

        //选择viewpage
        vp_fragment.setCurrentItem(page);
        curr_page = page;
    }

    private HomeActivity getCustomActivity() {
        return (HomeActivity) getActivity();
    }

    private void initData() {
        if (StrUtil.isNotEmpty(getCustomActivity().getIntent().getStringExtra("id"))) {
            Map<String, String> body = new HashMap<>();
            body.put("user_id", getCustomActivity().getIntent().getStringExtra("id"));
            body.put("token", DataManger.getInstance().getUserInfo().token);
            bOkHttpManager.httpRequest(Constant.RequestType.SEND_MESSAGE, Constant.Http.POST, body, false, new
                    TypeToken<Response<Void, ArrayList<? extends IIrrigatedAreaFilter>>>() {
                    }.getType(), true, false);
        }
    }

    @Override
    protected void onPostHandle(int requestType, Object response, boolean error, int errorCode, Object obj1, Object obj2) {
        super.onPostHandle(requestType, response, error, errorCode, obj1, obj2);
        if (error) {
            BToast.getInstance().show(getResources().getString(R.string.abnormal));
        } else {
            if (response == null) {
                BToast.getInstance().show(getResources().getString(R.string.datafailure));
            } else {
                if (requestType == Constant.RequestType.SEND_MESSAGE) {
                    Response<Void, List<? extends IIrrigatedAreaFilter>> result = (Response<Void, List<? extends IIrrigatedAreaFilter>>) response;
                    if (result.getCode() == 0) {
                    } else {
                        BToast.getInstance().show(result.getMsg());
                    }
                }
            }
        }
    }
}

